import React, { useState, useEffect, useReducer } from 'react';
import { Form, Button, Row, Card, Popconfirm, message } from 'antd';
import UserForm from './user-form';
import UserListTable from './user-list-table';
import UserModal from './user-modal';
import { getList, listInitState, deleteUser } from 'hook/userList';
import './index.less';

const UserManage = props => {
    const { form } = props;
    
    const [userDate, setUserDate] = useState(listInitState);
    const [selectedRowKeys, setRowKeys] = useState([]);
    const [modalVisible, setModalVisible] = useState(false);
    const [tableCondition, setTableCondition] = useState({
        offset: 0,
        limit: 10,
        filters: {}
    });
    const [editorId, setEditorId] = useState(0);

    useEffect(() => {
        handleFetchList();
    }, [tableCondition]);

    // 请求错误回调
    function errorCb(err) {
        message.error(err.msg || '请求失败');
        setUserDate({
            ...userDate,
            loading: false,
            error: err
        });
    }
    // 请求列表数据
    function handleFetchList() {
        const { getFieldsValue } = form;
        const formValue = getFieldsValue(['search_chineseName']);
        const { filters } = tableCondition;
        const conditions = { ...tableCondition, ...formValue };
        Reflect.deleteProperty(conditions, 'filters');
        // 删除所有没有实际值的条件
        for (const [key, val] of Object.entries(conditions)) {
            const actualVal = typeof val === 'string' ? val.trim() : val;
            if (actualVal === undefined || actualVal === null || actualVal === '') {
                Reflect.deleteProperty(conditions, key);
            } else if (~key.indexOf('search_')) {
                Reflect.deleteProperty(conditions, key);
                conditions[key.split('search_')[1]] = actualVal;
            }
        }
        for (const [key, val] of Object.entries(filters)) {
            if (val !== undefined && val !== null) {
                conditions[key] = val;
            }
        }
        getList(conditions, setUserDate, errorCb);
    }
    // 表格条件改变
    function handleTableChange(pagination, filters) {
        const { current, pageSize } = pagination;
        setTableCondition({
            offset: (current - 1) * pageSize,
            limit: pageSize,
            filters
        });
    }

    // 点击删除
    const handleDelete = id => {
        deleteUser(id || selectedRowKeys, () => {
            if (!id) {
                setRowKeys([]);
            }
            message.success('删除成功');
            handleFetchList();
        }, res => message.error(res.msg));
    }

    // 点击编辑或新增
    const handleEditor = id => {
        setEditorId(id);
        setModalVisible(true);
    }

    return (
        <div className="user-manage-wrap">
            <div className="user-manage-form">
                <Card title="用户列表">
                    <UserForm
                        form={form}
                        onSubmit={handleFetchList}
                    />
                    <UserModal
                        form={form}
                        visible={modalVisible}
                        setModalVisible={setModalVisible}
                        setEditorId={setEditorId}
                        id={editorId}
                        handleFetchList={handleFetchList}
                    />
                    <Row style={{ marginBottom: 20 }}>
                        <Popconfirm
                            title="确认批量删除名单？"
                            onConfirm={() => handleDelete(undefined)}
                            okText="确定"
                            cancelText="取消"
                        >
                        {
                            selectedRowKeys.length > 0 && <Button type="danger">批量删除</Button>
                        }
                        </Popconfirm>
                    </Row>
                    <UserListTable
                        handleEditorModal={handleEditor}
                        rowSelection={{ selectedRowKeys, onChange: setRowKeys }}
                        data={userDate}
                        onChange={handleTableChange}
                        handleDelete={handleDelete}
                    />
                </Card>
            </div>
        </div>
    );
};

export default Form.create()(UserManage);